package com.mfs.proxy.client.transfer.http;

import java.nio.ByteBuffer;

/**
 * ByteBuffer 工具类
 *
 * @author mfs
 * @date 2023/7/20 22:40
 **/
public class ByteBufferUtil {
    /**
     * 获取一行，使用\r\n结束则为一行
     * 解析不到完整的一行则返回null
     * 字节缓存的position指针会回退
     *
     * */
    public static byte[] getALine(ByteBuffer byteBuffer) {
        Byte beforeByte = null;
        int beginPosition = byteBuffer.position();
        boolean lineEnd = false;
        while (byteBuffer.position() < byteBuffer.limit()) {
            byte aChar = byteBuffer.get();
            if (beforeByte != null && beforeByte == 13 && aChar == 10) {
                lineEnd = true;
                break;
            }
            beforeByte = aChar;
        }
        int endPosition = byteBuffer.position();
        if (lineEnd) {
            byte[] res = new byte[endPosition - beginPosition];
            System.arraycopy(byteBuffer.array(), beginPosition, res, 0, res.length);
            return res;
        } else {
            // 没有找到完整的一行，返回空，回溯position
            byteBuffer.position(beginPosition);
            return null;
        }
    }
}
